package pers.linkong.asr.web;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import pers.linkong.asr.domain.ImageBean;
import pers.linkong.asr.service.ImageService;
import pers.linkong.asr.util.ResultInfo;
import pres.linkong.as.fr.FaceRecognition;
import sun.misc.BASE64Decoder;

import com.mathworks.toolbox.javabuilder.MWException;

@SuppressWarnings("restriction")
@Controller
@RequestMapping("/img")
public class ImageController {

	@Autowired
	private ImageService imageService;
	
	@RequestMapping("/saveimg")
	@ResponseBody
	public ResultInfo saveimg(String image, int sid, HttpServletRequest request, HttpSession session) throws IOException {
		try {
			ImageBean imageBean = new ImageBean();
			int imgid = this.imageService.getlastimgid()+1;
			//保存图像
			String path = request.getServletContext().getRealPath("/WEB-INF/");
			System.out.println(path);
			BASE64Decoder decoder = new BASE64Decoder();    
	        byte[] b = decoder.decodeBuffer(image);    

	        ByteArrayInputStream bais = new ByteArrayInputStream(b);    
	        BufferedImage bi = ImageIO.read(bais); 
	        
	        BufferedImage newBufferedImage = new BufferedImage(bi.getWidth(),
	        		bi.getHeight(), BufferedImage.TYPE_INT_RGB);
	        //TYPE_INT_RGB:创建一个RBG图像，24位深度，成功将32位图转化成24位
	        newBufferedImage.createGraphics().drawImage(bi, 0, 0, Color.WHITE, null);
	        
	        File w2 = new File(path+"Train/",imgid+".jpg");    
	        ImageIO.write(newBufferedImage,"jpg",w2);
	        
	        imageBean.setImgid(imgid);
	        imageBean.setSid(sid);
	        this.imageService.addImage(imageBean);
	        return ResultInfo.data(0, "图片" + imgid + "保存成功");
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return ResultInfo.data(0, "发生异常，图片保存失败，请稍后再试");
		}

	}
	
	@RequestMapping("/train")
	@ResponseBody
	public ResultInfo train(HttpSession session, HttpServletRequest request) throws MWException {
		try {
			String path = request.getServletContext().getRealPath("/WEB-INF/");
			FaceRecognition fr = new FaceRecognition();
			Object[] result1 = fr.Train(1,path);
			System.out.println("Train:" + result1[0]);
			return ResultInfo.data(1, "训练成功");
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return ResultInfo.data(0, "发生异常，训练失败，请稍后再试");
		}
	}
}
